import os
import sys
import uuid
import shutil
import time

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from constants.paths import set_current_project_id, get_save_path, get_subtitle_split_results_path, get_subtitle_remerged_results_path
from core.config_utils import load_key
from core import (
    _01_download_audio,
    _02_transcribe,
    _03_split_sentences,
    _04_split_by_meaning,
    _05_summarize,
    _06_translate_all,
    _07_split_for_sub,
    _08_generate_timeline
)
from core.onekeycleanup import cleanup

def process_video_for_backend(project_id: str, destination_video_path: str, languages: list):
    """
    处理视频文件用于后端集成。

    Args:
        project_id: 项目ID。
        destination_video_path: 已保存的视频文件路径。
        languages: 目标翻译和字幕生成语言列表。
    """
    # 设置当前项目ID和保存路径 (已在api.py中完成，这里仅为确保上下文正确设置)
    set_current_project_id(project_id)
    # save_path = get_save_path() # 不再需要在这里获取save_path

    print(f"开始处理项目ID: {project_id}")
    print(f"正在处理文件: {destination_video_path}")

    try:
        print("开始转录音频...")
        _02_transcribe.transcribe()
        print("音频转录完成。")

        print("开始分句处理...")
        _03_split_sentences.split_by_spacy()
        _04_split_by_meaning.split_sentences_by_meaning()
        print("分句处理完成。")

        for lang in languages:
            print(f"开始处理语言: {lang}")

            print(f"{lang} 的摘要与翻译处理中...")
            _05_summarize.get_summary(lang)
            _06_translate_all.translate_all(lang)
            print(f"{lang} 的摘要与翻译完成。")

            print(f"{lang} 的字幕切分与对齐处理中...")
            _07_split_for_sub.split_for_sub_main(lang)
            _08_generate_timeline.align_timestamp_main(lang)
            print(f"{lang} 的字幕处理完成。")

        print("所有语言的视频处理已完成。")

        output_files = {}
        for lang in languages:
            output_files[f'subtitle_split_{lang}'] = get_subtitle_split_results_path(lang)
            output_files[f'subtitle_remerged_{lang}'] = get_subtitle_remerged_results_path(lang)

        return {"status": "success", "project_id": project_id, "output_files": output_files}

    except Exception as e:
        print(f"处理过程中发生错误: {e}")
        return {"status": "error", "project_id": project_id, "message": str(e)}


